library(shiny)
library(readr)

data <- read_csv2("data/amostra.csv")
brasil <- read_csv2("data/brasil.csv")
acidentes <- read_csv2("data/acidentes.csv")
data$hora_acidente <- sprintf("%04d", data$hora_acidente)

sct_data <- as.matrix(data[ , c("hora_acidente", "idade_cat", "ds_agente_causador")])

bar_data <- read_csv2("data/teste.csv")

choropleth_data <- read_csv2("data/puf.csv")

                                        # TODO rename functions
# This one generates a list for a tree or dendrogram
rsplit <- function(x) {
    x <- x[!is.na(x[,1]),,drop=FALSE]
    if(nrow(x)==0) return(NULL)
    if(ncol(x)==1) return(lapply(x[,1], function(v) list(name=v)))
    s <- split(x[,-1, drop=FALSE], x[,1])
    unname(mapply(function(v,n) {if(!is.null(v)) list(name=n, children=v)
                                 else list(name=n)},
                  lapply(s, rsplit), names(s), SIMPLIFY=FALSE))
}

# This one generates a list for a treemap
makeList <- function(x) {
  if(ncol(x) > 2) {
      listSplit <- split(x[-c(1)], x[1], drop=F)
      lapply(names(listSplit), function(y) {list(name = y,
                                                 value = as.integer(listSplit[[y]][1,1]),
                                                 children = makeList(listSplit[[y]][-1]))})
  } else {
      lapply(seq(nrow(x[1])), function(y) {list(name = as.character(x[y,1]),
                                                value = as.integer(x[y,2]))})
  }
}

treemap_data <- makeList(unique(acidentes))

tree_data <- rsplit(unique(brasil))[[1]]

server <- function(input, output, session) {

    observe({

        session$sendCustomMessage(type="scatterplot_values", message = sct_data)

    })

    observe({

        session$sendCustomMessage(type="dendrogram_values",
                                  message = c(tree_data, bar_data))

    })

    observe({

        session$sendCustomMessage(type="treemap2_values", message = treemap_data)

    })


    observe({

        session$sendCustomMessage(type="choropleth_values", message = choropleth_data)

    })
}
